/**
 * 
 */
package com.java.controller.front;

import java.sql.Timestamp;
import java.util.Date;
import java.util.UUID;

import javax.mail.MessagingException;
import javax.servlet.http.HttpServletRequest;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.servlet.ModelAndView;

import com.java.entity.User;
import com.java.service.impl.UserServiceImpl;
import com.java.utils.EmailUtills;
import com.java.utils.md5Utils;

/**
* @author Kidney
* 创建时间：2019年2月13日 下午8:52:53
* Description:
*/
/**
 * @author KIDNEY
 *
 */
@Controller
@RequestMapping(value = "/email/")
public class EmailController {

	@Autowired
	private UserServiceImpl us;

	@RequestMapping(value = "forgetPass")
	public ModelAndView forgetPass(HttpServletRequest request, String username) {
		User user = us.selectByName(username);
		String msg = "";
		ModelAndView mav = new ModelAndView();

		if (user == null) { // 用户名不存在
			msg = "用户名不存在,你不会忘记用户名了吧?";
			mav.getModel().put("msg", msg);
			mav.setViewName("/pages/email/beginReset.jsp");
			return mav;
		} else {
			String secretKey = UUID.randomUUID().toString();
			Timestamp outDate = new Timestamp(System.currentTimeMillis() + 30 * 60 * 1000);
			long date = outDate.getTime() / 1000 * 1000;
			String key = user.getUserName() + "$" + date + "$" + secretKey;
			String digitalSignature = md5Utils.md5(key);

			String title = "密码找回";
			String path = request.getContextPath();
			String basePath = request.getScheme() + "://" + request.getServerName() + ":" + request.getServerPort()
					+ path + "/";
			String resetPassHref = basePath + "email/reset_password.shtml?sid=" + digitalSignature + "&username="
					+ user.getUserName();

			String content = "请勿回复本邮件.点击下面的链接,重设密码<br/><a href=" + resetPassHref + " target='_BLANK'>" + resetPassHref
					+ "</a>" + "<br/>本邮件超过30分钟,链接将会失效";

			String emailAddress = user.getAddress();
			user.setSid(digitalSignature);
			user.setOutDate(outDate);
			us.updateByPrimaryKeySelective(user);

			// 测试
			System.out.println(emailAddress);
			System.out.print(resetPassHref);

			try {
				EmailUtills.sendEmail(emailAddress, title, content);
			} catch (MessagingException e) {
				msg = "邮箱不存在？请联系管理员花花。";
				e.printStackTrace();
			}

			msg = "邮件发送";
			mav.getModel().put("msg", msg);
			mav.setViewName("/pages/email/beginReset.jsp");
			return mav;

		}
	}

	@RequestMapping(value = "reset_password")
	public ModelAndView checkResetLink(String sid, String username) {
		ModelAndView mav = new ModelAndView();
		String msg = "";
		User user = us.selectByName(username);

		if (sid.equals("") || username.equals("")) {
			msg = "链接不完整,请重新生成";
			mav.getModel().put("msg", msg);
			mav.setViewName("/pages/email/resetError.jsp");
			return mav;
		}

		if (user == null) {
			msg = "链接错误,无法找到匹配用户,请重新申请找回密码.";
			mav.getModel().put("msg", msg);
			mav.setViewName("/pages/email/resetError.jsp");
			return mav;
		}

		Date outDate = user.getOutDate();
		if (outDate.getTime() <= System.currentTimeMillis()) { // 表示已经过期
			msg = "链接已经过期,请重新申请找回密码.";
			mav.getModel().put("msg", msg);
			mav.setViewName("/pages/email/resetError.jsp");
			return mav;
		}

		String digitalSignature = user.getSid(); // 数字签名

		if (!digitalSignature.equals(sid)) {
			msg = "链接不正确,是否已经过期了?重新申请吧";
			mav.getModel().put("msg", msg);
			mav.setViewName("/pages/email/resetError.jsp");
			return mav;
		}
		mav.getModel().put("username", username);
		mav.setViewName("/WEB-INF/resetPassword/reset.jsp");
		return mav;
	}

	@RequestMapping(value = "reset_begin")
	public ModelAndView beginReset(String username, String password1, String password2) {
		ModelAndView mav = new ModelAndView();

		if (password1.equals(password2)) {
			String refreshKey = UUID.randomUUID().toString();
			User selectedUser = us.selectByName(username);
			int selectedId = selectedUser.getUserId();
			User record = new User();
			record.setUserId(selectedId);
			record.setPassword(md5Utils.md5(password1));
			record.setSid(refreshKey);
			int flag = us.updateByPrimaryKeySelective(record);

			if(flag==1){
				mav.getModel().put("flag", "修改成功");
				mav.setViewName("redirect:/pages/email/resetScuess.jsp");
			}
			else{
				mav.getModel().put("error", "修改失败");
				mav.setViewName("/WEB-INF/resetPassword/reset.jsp");
			}

		} else {

			mav.getModel().put("error", "密码不相等");
			mav.setViewName("/WEB-INF/resetPassword/reset.jsp");
		}
		return mav;
	}

}
